<template>
	<div class="bg-white px-3" style="margin: -20px;margin-top: -1rem;margin-bottom: 0 !important;">
		<el-tabs v-model="tabIndex" @tab-click="getList">
		    <el-tab-pane :label="item.name" 
			v-for="(item, index) in tabbars" :key="index">
				
			</el-tab-pane>
		</el-tabs>
		
		<button-search placeholder="搜索的商品名称"
		@search="searchEvent"
		ref="buttonSearch">
			<template #left>
				<router-link :to="{name:'shop_goods_create'}" class="mr-2">
					<el-button type="success" size="mini">发布商品</el-button>
				</router-link>
				
				<el-button type="warning" size="mini"
				v-if="tab === 'delete'"
				@click="restore">恢复商品</el-button>
				<el-button type="danger" size="mini"
				v-if="tab == 'delete'"
				@click="trueMultiDelete">彻底删除</el-button>
				<el-button type="danger" size="mini"
				v-if="tab != 'delete'"
				@click="deleteAll">批量删除</el-button>
				<el-button size="mini"
				v-if="tab == 'all' || tab == 'off'"
				@click="changeStatus(1)">上架</el-button>
				<el-button size="mini"
				v-if="tab == 'all' || tab == 'saling'"
				@click="changeStatus(0)">下架</el-button>
			</template>
			<!-- 高级搜索表单 -->
			<template #form>
				<el-form inline ref="form" :model="form" label-width="80px">
					<el-form-item label="商品名称" class="mb-0">
						<el-input v-model="form.title" placeholder="请输入商品名称" size="mini"></el-input>
					</el-form-item>
					<el-form-item label="商品分类" class="mb-0">
						<el-button @click="isShowCheckCategory = true">
							{{checkedKeys.length >= 1 ? '修改分类' : '选择分类'}}
						</el-button>
						<span class="ml-1 badge badge-info">{{checkedKeys.length >= 1 ? checkedKeys[0].name : '未选择分类'}}</span>
					</el-form-item>
					<el-form-item class="mb-0">
						<el-button class="ml-2" type="info" size="mini" @click="searchEvent">搜索</el-button>
						<el-button type="info" size="mini" @click="clearSearch">清空筛选条件</el-button>
					</el-form-item>
				</el-form>
			</template>
		</button-search>
		<!-- 商品列表 -->
		<el-table border
		class="mt-3"
		:data="tableData"
		style="width: 100%"
		@selection-change="handleSelectionChange">
		  <el-table-column
			type="selection"
			width="45"
			align="center">
			</el-table-column>
		  <el-table-column label="商品信息" width="350">
			<template slot-scope="scope">
				<div class="media">
					<img class="mr-2" :src="scope.row.cover" style="width: 60px;" scope="widthFix"/>
					<div class="media-body">
						<p class="mt-0">{{scope.row.title}}</p>
						<p class="mb-0">分类:{{scope.row.category.name}}</p>
						<p class="mb-0">时间:{{scope.row.create_time}}</p>
					</div>
				</div>
			</template>
		  </el-table-column>
		  <el-table-column prop="sale_count" width="60" label="销量">
		  </el-table-column>
		
		<el-table-column label="商品状态" width="100" >
			<template slot-scope="scope">
				<span class="badge " :class="scope.row.status ? 'badge-success' : 'badge-danger'">
					{{scope.row.status ? '上架' : '仓库'}}
				</span>
			</template>
		</el-table-column>
		<el-table-column label="审核" width="120" >
			<template slot-scope="scope">
				<div class="d-flex flex-column algin-items-center"
				v-if="!scope.row.ischeck">
					<el-button type="success" size="mini" plain
					@click="checkGoods(scope.row, 1)">审核通过</el-button>
					<el-button class="ml-0 mt-2" type="danger" size="mini" plain
					@click="checkGoods(scope.row, 2)">审核拒绝</el-button>
				</div>
				<span v-else>{{scope.row.ischeck === 1 ? '已通过' : '已拒绝'}}</span>
			</template>
		</el-table-column>
		<el-table-column
			prop="stock"
			width="100"
			label="总库存">
		</el-table-column>
		<el-table-column
		prop="pprice"
		label="价格"
		width="120">
			<template slot-scope="scope">
				<div class="d-flex flex-column algin-items-center">
					<div style="display: inline-flex;">
						售价:&nbsp;<span class="text-danger">¥{{scope.row.min_price}}</span>
					</div>
					<div style="display: inline-flex;">
						原价:&nbsp;<span class="text-muted">¥{{scope.row.min_oprice}}</span>
					</div>
				</div>
			</template>
		</el-table-column>
		<el-table-column label="操作" width="500">
			<template slot-scope="scope">
				<el-button type="text" size="mini" 
				@click="navigate('shop_goods_create', scope.row.id)">基础设置</el-button>
				<el-button type="text" size="mini" 
				@click="navigate('shop_goods_sku', scope.row.id)"
				:class="(scope.row.sku_type == 0 && !scope.row.sku_value) || (scope.row.sku_type == 1 && !scope.row.goods_skus.length) ? 'text-danger' : ''">商品规格</el-button>
				<el-button type="text" size="mini"  
				@click="navigate('shop_goods_attr', scope.row.id)"
				:class="scope.row.goods_attrs.length === 0 ? 'text-danger' : ''">商品属性</el-button>
				<el-button type="text" size="mini"  
				@click="navigate('shop_goods_banner', scope.row.id)"
				:class="scope.row.goods_banner.length === 0 ? 'text-danger' : ''">轮播图</el-button>
				<el-button type="text" size="mini"  
				@click="navigate('shop_goods_content', scope.row.id)"
				:class="!scope.row.content ? 'text-danger' : ''">商品详情</el-button>
				<el-button type="text" size="mini"  >折扣设置</el-button>
				<el-button type="text" size="mini" 
				@click="deleteItem(scope.row)">删除商品</el-button>
			</template>
		</el-table-column>
		</el-table>
		<div style="height: 60px;"></div>
		<el-footer class="d-flex border-top align-items-center px-0 position-fixed bg-white"
		style="bottom: 0;left: 200px;right: 0;z-index: 10;">
			<div class="px-2" style="flex: 1;">
				<el-pagination
				 @size-change="handleSizeChange" 
				 @current-change="handleCurrentChange" 
				 :current-page="page.current"
				 :page-sizes="page.sizes" 
				 :page-size="page.size" 
				 layout="total, sizes, prev, pager, next, jumper" 
				 :total="page.total">
				</el-pagination>
			</div>
		</el-footer>
		
		<!-- 选择商品分类抽屉 -->
		<el-drawer
			title="选择商品分类"
			:visible.sync="isShowCheckCategory"
			direction="rtl"
			size="40%"
			:before-close="handleClose"
			>
			
			<div style="position: absolute;top: 52px;left: 0;right: 0;bottom: 0;">
				<div style="position: absolute;top: 0;right: 0;left: 0;bottom: 60px;overflow-y: auto;">
					<el-tree
					  ref="tree"
					  :data="cateOptions"
					  show-checkbox
					  node-key="id"
					  default-expand-all
					  :default-checked-keys="checkedKeys"
					  :check-strictly="true"
					  @check="check"
					  :props="defaultProps"
					  style="align-items: center;">
					</el-tree>
				</div>
				<div style="height: 60px;position: absolute;bottom: 0;right: 0;left: 0;"
				class="border d-flex align-items-center bg-white">
					<el-button type="primary" class="ml-2" @click="isShowCheckCategory = false">确定</el-button>
					<el-button type="warning" class="ml-2" @click="cleanCategory">清空</el-button>
				</div>
			</div>
			
		</el-drawer>
	</div>
</template>

<script>
import buttonSearch from "@/components/common/button-search.vue"
import common from "@/common/mixins/common.js";
	
export default {
	mixins:[common],
	inject:['layout'],
	
	components: {
		buttonSearch,
	},
	
	created() {
		
	},
	
	data() {
		return {
			//tree checkedKeys
			checkedKeys:[],
			
			//tree 节点名称
			defaultProps: {
				children: 'child',
				label: 'name'
			},
			//是否显示选择商品分类抽屉
			isShowCheckCategory: false,
			
			cateOptions: [],
			
			preUrl: 'goods',
			
			tabIndex: 0,
			tabbars: [
				{name:"全部", key: 'all'},
				{name:"审核中", key: 'checking'},
				{name:"出售中", key: 'saling'},
				{name:"已下架", key: 'off'},
				{name:"库存预警", key: 'min_stock'},
				{name:"回收站", key: 'delete'},
			],
			form: {
				title: '',
				category_id: '',
			},
			superSearch: false,
			tableData: [],
			
			//当前页
			currentPage: 1,
		}
	},
	
	computed: {
		tab() {
			return this.tabbars[this.tabIndex].key
		},
		
		params() {
			let str  = ''
			for (let key in this.form) {
				let val = this.form[key]
				if(val){
					if(Array.isArray(val)) {
						str += `&starttime=${val[0]}`
						str += `&endtime=${val[1]}`
					} else {
						str += `&${key}=${val}`
					}
				}
			}
			return str
		}
	},
	
	methods: {
		//审核商品
		checkGoods(item, ischeck) {
			this.layout.showLoading()
			this.axios.post('/admin/goods/' + item.id + '/check',{
				ischeck: ischeck
			}, {token : true}).then(res => {
				this.getList()
				this.$message({
					message: ischeck == 1 ? '商品审核成功' : '商品审核失败',
					type: 'success'
				});
				this.layout.hideLoading()
			}).then(err => {
				this.layout.hideLoading()
			})
		},
		//navigate
		navigate(name, id) {
			this.$router.push({
				name,
				params: {id}
			})
		},
		
		//上架下架
		changeStatus(status) {
			if(this.ids.length == 0) {
				return this.$message({
						message: '请选择要操作的商品',
						type: 'error'
					});
			}
			this.showLoading()
			this.axios.post('/admin/goods/changestatus', {
					ids: this.ids,
					status
				}, {token: true})
				.then(res => {
					this.hideLoading()
					this.getList()
					this.$message({
						message: (status == 1 ? '上架' : '下架') + '成功',
						type: 'success'
					});
				}).catch(err => {
					this.hideLoading()
				})
		},
		
		//恢复商品
		restore() {
			this.operationGoodsByIds('restore')
		},
		
		//彻底删除商品
		trueMultiDelete() {
			this.operationGoodsByIds('destroy')
		},
		
		//根据ids操作商品
		operationGoodsByIds(operation) {
			if(this.ids.length == 0) {
				return this.$message({
						message: '请选择要操作的商品',
						type: 'error'
					});
			}
			this.showLoading()
			this.axios.post('/admin/goods/' + operation, {ids: this.ids}, {token: true})
				.then(res => {
					this.hideLoading()
					this.getList()
					this.$message({
						message: '操作成功',
						type: 'success'
					});
				}).catch(err => {
					this.hideLoading()
				})
		},
		
		//权限树check事件
		check(...e) {
			if(e[1].checkedKeys.length > 1) {
				this.$message({
					message: '最多选择一个分类',
					type: 'warning'
				});
			}
			this.$refs.tree.setCheckedKeys([e[0].id])
			this.checkedKeys = [e[0]]
			this.form.category_id = e[0].id
		},
		
		//清空分类勾选
		cleanCategory() {
			this.$refs.tree.setCheckedKeys([])
			this.checkedKeys = []
			this.form.category_id = 0
		},
		
		// model关闭之前
		handleClose(done) {
			this.$confirm('确认关闭？')
				.then(_ => {
					done();
				})
				.catch(_ => {})
		},
		
		//getListUrl
		getListUrl() {
			return `/admin/${this.preUrl}/${this.page.current}?limit=${this.page.size}&tab=${this.tab}${this.params}`
		},
		
		//getListResult
		getListResult(e) {
			this.tableData = e.list
			let r = {
				id: -1,
				name: '',
				child: [],
				disabled: true,
			}
			this.list2tree(e.cates, 0, r)
			this.cateOptions = r.child
		},
		
		//list扁平结构数据 -> tree那种结构
		list2tree(list, pid, node) {
			let pArr = list.filter(x => x.category_id == pid)
			if(pArr.length < 1) {
				node.disabled = false
				return
			}
			for(let p of pArr) {
				let tmp = {
					id: p.id,
					name: p.name,
					child: [],
					disabled: false,
					//可以配置成true只让选择最后一级的分类
				}
				node.child.push(tmp)
				this.list2tree(list, p.id, tmp)
			}
		},
		
		//清空搜索条件
		clearSearch() {
			this.form = {
				title: '',
				category_id: '',
			}
			this.$refs.tree.setCheckedKeys([])
			this.checkedKeys = []
		},
		//搜索事件
		searchEvent(e = false) {
			if (typeof e === 'string') {
				this.form.title = e
			} 
			this.getList()
		},
		
	}
}
</script>

<style>

	.el-tree-node__content > label.el-checkbox {
		margin: 8px;
	}
</style>
